from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, ListCreateAPIView
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, DestroyModelMixin, ListModelMixin

from goods.models import SKU
from goods.serializers import SKUListSerializer
from .models import User
from . import constants
from . import serializers


class UsernameCountView(APIView):
    """
    判断用户名是否存在
    """

    def get(self, request, username):
        # 获取数据库中该用户名的数量
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


class MobileCountView(APIView):
    """
    判断手机号是否存在
    """

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)


class UserCreateAPIView(CreateAPIView):
    """
    创建用户
    """
    serializer_class = serializers.UserCreateSerializer


class UserDetailView(RetrieveAPIView):
    serializer_class = serializers.UserDetailSerializer
    # 用户只有登陆后才能访问此页面
    permission_classes = [IsAuthenticated]

    # RetrieveAPIView 里查询是默认从路径中接收主键后查询，所以重写get_object方法
    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]

    serializer_class = serializers.EmailSerializer

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    def get(self, request):

        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        user = User.check_verify_email_token(token)

        if not user:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)

        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})


# 分析，需要创建和修改，创建本可以直接用CreatModelViewset,但是这是按照传入的数据直接创建，然而地址模型类里有用户，而前端输入传过来的没有
# 所有需要从请求体中获取，需要重写create方法，并且修改的时候需要定义
class UserAddressViewSet(GenericViewSet, CreateModelMixin, UpdateAPIView):
    # 序列化器，继承类需要用到，下面自己定义的方式用不到
    serializer_class = serializers.UserAddressSerializer
    # 登陆后才能访问
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # 获取列表，为什么不用listModelmixin,因为返回的数据内容不能满足要求
    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()

        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        创建用户地址数据
        """
        count = request.user.addresses.filter(is_deleted=True).count()

        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已到达上线'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # DELETE /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        address = self.get_object()

        request.user.default_address = address

        request.user.save()

        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        address = self.get_object()

        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data)


# 方式１
class UserBrowsingHistoryView(CreateAPIView, ListModelMixin):
    serializer_class = serializers.AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user_id = request.user.id

        redis_cli = get_redis_connection('history')
        # 获取redis中的浏览记录(list)
        history = redis_cli.lrange('history_%d' % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT)
        skus = []
        # 为了保持查询出的顺序与用户的浏览历史保存顺序一致，如果用查询SKU.objects.filter(id__id())查出的结果和流浪的顺序可能不一致
        # 这里可能存在一个问题，商品可能下架了
        for sku_id in history:
            skus.append(SKU.objects.get(id=sku_id))

        serializer = SKUListSerializer(skus, many=True)
        return Response(serializer.data)


# 方式２,有点问题图片出不来，返回给前端的结果都一样
# class UserBrowsingHistoryView(ListCreateAPIView):
#     def get_serializer_class(self):
#         if self.request.method == 'GET':
#             return SKUListSerializer
#         else:
#             return serializers.AddUserBrowsingHistorySerializer
#
#     def get_queryset(self):
#
#         user_id = self.request.user.id
#
#         redis_cli = get_redis_connection('history')
#         # 获取redis中的浏览记录(list)
#         history = redis_cli.lrange('history_%d' % user_id, 0, -1)
#
#         skus = []
#         for sku_id in history:
#             skus.append(SKU.objects.get(id=sku_id))
#
#         return skus
